/**
 * VIP会员权益页面
 * 展示用户VIP状态、会员权益、使用说明等信息
 */
import React, { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';

/**
 * 会员权益项目接口定义
 */
interface VipBenefit {
  id: number;          // 权益ID
  title: string;       // 权益标题
  description: string; // 权益描述
  icon: string;        // 权益图标
  color: string;       // 权益主题色
}

/**
 * VIP状态接口定义
 */
interface VipStatus {
  isVip: boolean;           // 是否是VIP会员
  level: string;            // 会员等级
  expireDate: string | null; // 会员到期时间
  benefits: string[];       // 会员权益列表
}

export default function Vipqy() {
  // 路由导航hook
  const navigate = useNavigate();
  
  // 状态管理
  const [benefits, setBenefits] = useState<VipBenefit[]>([]); // 权益列表
  const [vipStatus, setVipStatus] = useState<VipStatus | null>(null); // VIP状态
  const [loading, setLoading] = useState(true); // 加载状态
  const [userName, setUserName] = useState<string | null>(null); // 用户名

  // 主题色定义
  const mainBlue = '#4FC3F7';   // 主要蓝色
  const lightBlue = '#B3E5FC';  // 浅蓝色
  const borderBlue = '#81D4FA'; // 边框蓝色

  useEffect(() => {
    // 从localStorage获取用户名
    const name = localStorage.getItem('userName');
    setUserName(name);

    /**
     * 获取会员权益和状态数据
     * 包括会员权益列表和当前用户的VIP状态
     */
    const fetchData = async () => {
      try {
        // 获取会员权益列表
        const benefitsRes = await fetch('/hongbao-lzt/vip-benefits');
        const benefitsData = await benefitsRes.json();
        if (benefitsData.success) {
          setBenefits(benefitsData.data);
        }
        
        // 获取会员状态
        const statusRes = await fetch(`/hongbao-lzt/vip-status?userName=${encodeURIComponent(name || '')}`);
        const statusData = await statusRes.json();
        if (statusData.success) {
          setVipStatus(statusData.data);
        }
        setLoading(false);
      } catch (error) {
        console.error('获取数据失败:', error);
        setLoading(false);
      }
    };
    fetchData();
  }, []);

  // 添加页面焦点事件监听，确保每次进入页面都刷新数据
  useEffect(() => {
    const handleFocus = () => {
      const name = localStorage.getItem('userName');
      if (name) {
        fetch(`/hongbao-lzt/vip-status?userName=${encodeURIComponent(name)}`)
          .then(res => res.json())
          .then(data => {
            if (data.success) {
              setVipStatus(data.data);
            }
          })
          .catch(error => console.error('刷新会员状态失败:', error));
      }
    };

    // 监听页面可见性变化
    document.addEventListener('visibilitychange', handleFocus);
    // 监听页面焦点
    window.addEventListener('focus', handleFocus);

    return () => {
      document.removeEventListener('visibilitychange', handleFocus);
      window.removeEventListener('focus', handleFocus);
    };
  }, []);

  // 加载状态显示
  if (loading) {
    return (
      <div style={{ 
        minHeight: '100vh', 
        background: '#fff', 
        display: 'flex', 
        alignItems: 'center', 
        justifyContent: 'center' 
      }}>
        {/* 加载动画 */}
        <div style={{ 
          width: 40, 
          height: 40, 
          border: `3px solid ${lightBlue}`, 
          borderTop: `3px solid ${mainBlue}`, 
          borderRadius: '50%', 
          animation: 'spin 1s linear infinite' 
        }}></div>
        {/* 加载动画样式 */}
        <style>{`
          @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
          }
        `}</style>
      </div>
    );
  }

  return (
    <div style={{ 
      minHeight: '100vh', 
      background: '#fff', 
      color: '#111', 
      fontFamily: 'PingFang SC, Arial' 
    }}>
      {/* 顶部导航栏 */}
      <div style={{ 
        display: 'flex', 
        alignItems: 'center', 
        height: 44, 
        padding: '0 10px',
        borderBottom: `1px solid ${borderBlue}`,
        background: `linear-gradient(135deg, ${mainBlue} 0%, ${borderBlue} 100%)`
      }}>
        {/* 返回按钮 */}
        <div style={{ 
          cursor: 'pointer', 
          marginRight: 6,
          color: '#fff'
        }} onClick={() => navigate(-1)}>
          <svg width="22" height="22" viewBox="0 0 24 24" fill="none">
            <path d="M15 19L8 12L15 5" stroke="#fff" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
          </svg>
        </div>
        {/* 页面标题 */}
        <div style={{ 
          fontWeight: 700, 
          fontSize: 17, 
          flex: 1,
          color: '#fff'
        }}>会员权益</div>
      </div>

      {/* 用户信息区域 */}
      <div style={{
        padding: '16px 12px 0 12px',
        fontSize: 15,
        color: mainBlue,
        fontWeight: 700
      }}>
        {userName ? (
          <span>当前用户：{userName}</span>
        ) : (
          <span>未登录</span>
        )}
      </div>

      {/* VIP状态卡片 */}
      <div style={{ 
        margin: '16px 12px 0 12px',
        background: vipStatus?.isVip 
          ? `linear-gradient(135deg, ${mainBlue} 0%, ${borderBlue} 100%)`
          : '#f5f5f5',
        borderRadius: 12,
        padding: '16px',
        color: vipStatus?.isVip ? '#fff' : '#111',
        position: 'relative',
        overflow: 'hidden'
      }}>
        {/* VIP标志装饰 */}
        <div style={{ 
          position: 'absolute', 
          top: -20, 
          right: -20, 
          fontSize: 60, 
          opacity: 0.1 
        }}>👑</div>
        {/* 会员状态显示 */}
        <div style={{ fontSize: 16, fontWeight: 700, marginBottom: 4 }}>
          {vipStatus?.isVip ? 'vip用户' : '普通用户'}
        </div>
        {/* 会员描述 */}
        <div style={{ fontSize: 12, opacity: 0.9 }}>
          {vipStatus?.isVip 
            ? '尊享专属权益，享受高品质服务'
            : '开通会员享受专属权益'
          }
        </div>
        {/* 会员到期时间 */}
        {vipStatus?.isVip && vipStatus?.expireDate && (
          <div style={{ 
            marginTop: 8, 
            fontSize: 11, 
            background: 'rgba(255,255,255,0.2)', 
            borderRadius: 6, 
            padding: '4px 8px',
            display: 'inline-block'
          }}>
            有效期至：{vipStatus.expireDate}
          </div>
        )}
      </div>

      {/* 会员权益列表区域 */}
      <div style={{ margin: '20px 12px 0 12px' }}>
        {/* 权益标题 */}
        <div style={{ 
          fontWeight: 700, 
          fontSize: 15, 
          marginBottom: 12, 
          color: '#111',
          display: 'flex',
          alignItems: 'center'
        }}>
          {/* 装饰条 */}
          <div style={{ 
            width: 4, 
            height: 16, 
            background: mainBlue, 
            borderRadius: 2, 
            marginRight: 8 
          }}></div>
          专属权益
        </div>
        
        {/* 权益卡片网格 */}
        <div style={{ 
          display: 'grid', 
          gridTemplateColumns: 'repeat(2, 1fr)', 
          gap: 12 
        }}>
          {/* 遍历渲染权益卡片 */}
          {benefits.map((benefit) => (
            <div key={benefit.id} style={{
              background: '#f8f9fa',
              borderRadius: 12,
              padding: '16px 12px',
              border: `1px solid ${borderBlue}`,
              position: 'relative',
              overflow: 'hidden',
              opacity: vipStatus?.isVip ? 1 : 0.6
            }}>
              {/* 权益图标 */}
              <div style={{
                position: 'absolute',
                top: 8,
                right: 8,
                fontSize: 20
              }}>
                {benefit.icon}
              </div>
              {/* 权益标题 */}
              <div style={{
                fontSize: 14,
                fontWeight: 700,
                color: '#111',
                marginBottom: 4,
                marginRight: 30
              }}>
                {benefit.title}
              </div>
              {/* 权益描述 */}
              <div style={{
                fontSize: 11,
                color: '#666',
                lineHeight: 1.4
              }}>
                {benefit.description}
              </div>
              {/* 装饰条 */}
              <div style={{
                position: 'absolute',
                bottom: 0,
                left: 0,
                width: '100%',
                height: 3,
                background: `linear-gradient(90deg, ${benefit.color} 0%, ${lightBlue} 100%)`
              }}></div>
            </div>
          ))}
        </div>
      </div>

      {/* 使用说明区域 */}
      <div style={{ margin: '20px 12px 0 12px' }}>
        {/* 说明标题 */}
        <div style={{ 
          fontWeight: 700, 
          fontSize: 15, 
          marginBottom: 12, 
          color: '#111',
          display: 'flex',
          alignItems: 'center'
        }}>
          {/* 装饰条 */}
          <div style={{ 
            width: 4, 
            height: 16, 
            background: mainBlue, 
            borderRadius: 2, 
            marginRight: 8 
          }}></div>
          使用说明
        </div>
        
        {/* 说明内容 */}
        <div style={{ 
          background: '#f8f9fa', 
          borderRadius: 12, 
          padding: '16px',
          border: `1px solid ${borderBlue}`
        }}>
          {/* 折扣说明 */}
          <div style={{ 
            fontSize: 12, 
            color: '#666', 
            lineHeight: 1.6,
            marginBottom: 8
          }}>
            • 商品9折优惠：购买商品时自动享受9折优惠
          </div>
          {/* 发货特权说明 */}
          <div style={{ 
            fontSize: 12, 
            color: '#666', 
            lineHeight: 1.6
          }}>
            • 优先发货：订单优先处理，快速发货
          </div>
        </div>
      </div>

      {/* 底部操作按钮 */}
      <div style={{ 
        margin: '20px 12px 16px 12px',
        padding: '0 12px'
      }}>
        <button
          style={{
            width: '100%',
            background: `linear-gradient(135deg, ${mainBlue} 0%, ${borderBlue} 100%)`,
            color: '#fff',
            border: 'none',
            borderRadius: 12,
            padding: '14px 0',
            fontWeight: 700,
            fontSize: 16,
            cursor: 'pointer',
            boxShadow: `0 4px 12px ${mainBlue}40`
          }}
          onClick={() => navigate('/app/vip')}
        >
          {vipStatus?.isVip ? '续费vip' : '开通vip'}
        </button>
      </div>
    </div>
  );
}
